package com.xxx.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.xxx.common.utils.R;
import com.xxx.common.utils.ShiroUtils;
import com.xxx.modules.sys.domain.SysUserDomain;
import com.xxx.modules.sys.service.SysUserLoginService;
import com.xxx.modules.sys.service.UserService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**用户登录 Controller
 * Created by ChenXuefei on 2017/10/12.
 */
@RestController
public class SysUserLoginController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Producer producer;
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserLoginService sysUserLoginService;
    /**
     * 生成验证码
     */
    @RequestMapping("captcha.jpg")
    public void createCaptcha(HttpServletResponse response) throws IOException {
        //设置不被缓存
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY,text);
        ServletOutputStream output = response.getOutputStream();
        ImageIO.write(image,"jpg",output);
        IOUtils.closeQuietly(output);
    }

    @RequestMapping(value="sys/login",method = RequestMethod.POST)
    public R sysUserLogin(String username,String password,String captcha){
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equals(kaptcha)){
            R.error("验证码不正确");
        }
        SysUserDomain userDomain = userService.queryUserByUserName(username);
        if(userDomain==null||userDomain.getPassword().equals(new Sha256Hash(password, userDomain.getSalt()).toHex())){
            return R.error("用户名或密码不正确");
        }

        if(userDomain.getStatus()==0){
            return R.error("该账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库中
        R r = sysUserLoginService.saveToken(userDomain.getUserId());
        return r;
    }

    /**
     * 退出登陆时，修改用户的token值
     * @return
     */
    @RequestMapping(value = "sys/logout",method = RequestMethod.POST)
    public R logout(){
        sysUserLoginService.updateUserToken(AbstractController.getUserId());
        return R.ok();
    }


}
